'use strict';

const Controller = require('egg').Controller;

class InterviewExperienceController extends Controller {
  // 获取经验列表（支持分页和搜索）
  async index() {
    const { ctx } = this;
    const { page = 1, pageSize = 5, keyword } = ctx.query;
    
    try {
      const result = await ctx.service.interviewExperience.findAll({
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        keyword
      });
      
      ctx.body = {
        code: 200,
        message: '获取经验列表成功',
        data: result.data,
        pagination: result.pagination,
      };
    } catch (error) {
      ctx.logger.error('获取经验列表失败:', error);
      ctx.body = {
        code: 500,
        message: '获取经验列表失败',
        data: null,
      };
    }
  }

  // 获取经验详情
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const experience = await ctx.service.interviewExperience.findById(id);
      if (experience) {
        ctx.body = {
          code: 200,
          message: '获取经验详情成功',
          data: experience,
        };
      } else {
        ctx.body = {
          code: 404,
          message: '经验不存在',
          data: null,
        };
      }
    } catch (error) {
      ctx.logger.error('获取经验详情失败:', error);
      ctx.body = {
        code: 500,
        message: '获取经验详情失败',
        data: null,
      };
    }
  }

  // 创建经验
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    
    // 从JWT token中获取用户ID
    const userId = ctx.user?.id;
    if (!userId) {
      ctx.body = {
        code: 401,
        message: '未登录',
        data: null
      };
      return;
    }
    data.user_id = userId;
    
    try {
      const experience = await ctx.service.interviewExperience.create(data);
      ctx.body = {
        code: 200,
        message: '创建经验成功',
        data: experience,
      };
    } catch (error) {
      ctx.logger.error('创建经验失败:', error);
      ctx.body = {
        code: 500,
        message: '创建经验失败',
        data: null,
      };
    }
  }

  // 删除经验
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const result = await ctx.service.interviewExperience.delete(id);
      if (result) {
        ctx.body = {
          code: 200,
          message: '删除经验成功',
          data: null,
        };
      } else {
        ctx.body = {
          code: 404,
          message: '经验不存在',
          data: null,
        };
      }
    } catch (error) {
      ctx.logger.error('删除经验失败:', error);
      ctx.body = {
        code: 500,
        message: '删除经验失败',
        data: null,
      };
    }
  }
}

module.exports = InterviewExperienceController;
